package pl.us.ij.plugins.segmentation.commands.filters;

import ij.process.FloatProcessor;
import pl.us.ij.plugins.segmentation.infrastructure.Command;
import pl.us.ij.plugins.segmentation.infrastructure.exceptions.BreakCommandException;

/**
 * Created by IntelliJ IDEA.
 * User: Przemek
 * Date: 2010-01-08
 * Time: 00:15:37
 * To change this template use File | Settings | File Templates.
 */
public class AveragedFilterCommand extends Command<FilterCommandParams> {
//    @Override
    protected void processImage(FloatProcessor ip) {

        int width = ip.getWidth();
        int height = ip.getHeight();

        int iterationCount = getParams().getIterationCount();

        while (iterationCount-- > 0) {
            float[] outPixels = (float[]) ip.getPixels();
            float[] pixels = outPixels.clone();

            for (int y = 1; y < height - 1; y++) {
                int shift0 = (y - 1) * width;
                int shift1 = (y) * width;
                int shift2 = (y + 1) * width;
                int shiftD = y * width;
                for (int x = 1; x < width - 1; x++) {
                    float sum = pixels[shift0 + (x - 1)] +
                            pixels[shift0 + (x)] +
                            pixels[shift0 + (x + 1)] +
                            pixels[shift1 + (x - 1)] +
                            pixels[shift1 + (x)] +
                            pixels[shift1 + (x + 1)] +
                            pixels[shift2 + (x - 1)] +
                            pixels[shift2 + (x)] +
                            pixels[shift2 + (x + 1)];

                    outPixels[shiftD + x] = Math.round(sum / 9);
                }
            }

//            ip.setPixels(outPixels);
        }

//        getImageProcessor().setPixels(0, (FloatProcessor) ip);
    }

//    @Override
    protected void process(FloatProcessor fp) throws BreakCommandException {
        processImage(fp);
    }
}
